package com.jrauto.CarAppBackend.config;

import com.jrauto.CarAppBackend.filter.JwtAuthenticationFilter;
import com.jrauto.CarAppBackend.service.impl.CustomUserDetailsService;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import java.util.List;

/**
 * @author : huiMing
 * Date : 2025年06月23日 10:29
 * @version V1.0
 * Spring Security 配置类
 */
@Configuration // 声明为配置类
@EnableWebSecurity // 启用 Spring Security 的 Web 安全功能
public class SecurityConfig {

    @Resource
    private CustomUserDetailsService customUserDetailsService; // 重新注入 CustomUserDetailsService

    @Resource
    private JwtAuthenticationFilter jwtAuthenticationFilter; // 注入 JWT 认证过滤器
    /**
     * 配置密码编码器
     * BCryptPasswordEncoder 是一种安全的密码哈希算法，每次加密结果都不同，增加安全性
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 配置认证管理器
     * Spring Security 会使用 AuthenticationManager 来处理认证请求
     *
     * @return 认证管理器
     */
//    @Bean
//    public AuthenticationManager authenticationManager() {
//        DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
//        authenticationProvider.setUserDetailsService(customUserDetailsService); // 设置为 customUserDetailsService
//        authenticationProvider.setPasswordEncoder(passwordEncoder()); // 设置密码编码器
//        return new ProviderManager(authenticationProvider);
//    }

    // ✅ 推荐写法：通过 AuthenticationConfiguration 注入
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception {
        return authConfig.getAuthenticationManager();
    }

    // ✅ 推荐写法：把 DaoAuthenticationProvider 注册为 Bean
    @Bean
    public DaoAuthenticationProvider daoAuthenticationProvider() {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider(customUserDetailsService); // 👈 传入依赖
        provider.setPasswordEncoder(passwordEncoder());
        return provider;
    }


    /**
     * 配置安全过滤链
     *
     * @param http HttpSecurity 配置对象
     * @return SecurityFilterChain 实例
     * @throws Exception 配置异常
     */
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.cors(cors -> cors.configurationSource(corsConfigurationSource())
                ).csrf(AbstractHttpConfigurer::disable) // 🔥 禁用 CSRF
                .authorizeHttpRequests(auth -> auth.
                                // ⭐️ 允许所有 OPTIONS 请求无认证访问
//                        requestMatchers(HttpMethod.OPTIONS, "/**").permitAll().
                        requestMatchers("/auth/**","/brand/**","/series/**","/configs/**","/car/**",
                        "/static/**","/search/**","/cos/**","/images/**", "/docs/**","/swagger/**","/swagger-ui/**",
        "/favorite/**","/upload/**","/chat/**","/websocket/chat","/check/**").permitAll().
                anyRequest().authenticated())
                .authenticationProvider(daoAuthenticationProvider()) // ✅ 注册 Provider
                // 配置会话管理为无状态，因为 JWT 认证是无状态的
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                // 在 UsernamePasswordAuthenticationFilter 之前添加 JWT 认证过滤器
                // 这意味着每个请求都会先通过 JwtAuthenticationFilter 验证 JWT Token
                .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
        // 其他安全配置...
        return http.build();
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowedOrigins(List.of("http://localhost:5177","https://jr.jrauto.top","http://jr.jrauto.top"));
        config.setAllowedMethods(List.of("GET", "POST","PUT", "DELETE", "OPTIONS")); // 将 OPTIONS 也加入允许的方法列表
        config.setAllowedHeaders(List.of("Authorization", "Content-Type"));
        config.setExposedHeaders(List.of("X-Custom-Header"));
        config.setMaxAge(3600L);
        config.setAllowCredentials(true);  // 允许携带 Cookie
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config); // 对所有路径应用 CORS 配置
        return source;
    }
}
